$(function () {
    $('.select-all').click(function () {
        var fullCheckBoxs = $(this).parent().parent().parent().parent().parent().parent().find('tbody').find('input[type="checkbox"]');
        if ($(this).prop('checked')) {
            fullCheckBoxs.prop('checked', true);
        } else {
            fullCheckBoxs.prop('checked', false);
        }
    });
});


function bindDatePicker() {
    $('.date-picker').datepicker({format: 'yyyy-mm-dd'}).on('changeDate.datepicker.amui', function (event) {
        var shelflife = $(this).data('shelflife');

        mathExpiryDate(this);

        $(this).datepicker('close');
    });
}
//药品
function query_contact_drugs() {
    $.post(query_url, {'entry_id': entry_id, 'typeid': 70}, function (rtn) {
        var html = [];
        if (rtn.data.length > 0) {
            var total_purchase_num = 0;
            for (var index in rtn.data) {
                if (rtn.data[index].purchase_num <= 0) {
                    continue;
                }
                total_purchase_num += rtn.data[index].purchase_num;
                var id = "'" + rtn.data[index].Id + "'";
                html.push('<tr rowid="' + index + '">');
                html.push('<td><div class="checkbox"><label><input type="checkbox"></label></div></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Id + '" name="id" style="display: none;" readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Products.Id + '" name="goods_id"  readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Products.ShelfLife + '" name="shelf_life" readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Snd.id + '" name="snd_id" readonly="true"/></td>');
                html.push('<td td_name="goods_name">' + productGroupName(rtn.data[index].Products) + '</td>');
                if (rtn.data[index].lot_number) {
                    html.push('<td><input name="lot_number" value="' + rtn.data[index].lot_number + '" readonly="readonly" style="background:#fafafa;" type="text"></td>');
                } else {
                    html.push('<td><input name="lot_number"  type="text"></td>');
                }
                if (rtn.data[index].manufacture_date) {
                    html.push('<td><input name="manufacture_date" value="' + rtn.data[index].manufacture_date + '" type="text" readonly="readonly" style="background:#fafafa;" ></td>');
                } else {
                    html.push('<td><input  name="manufacture_date" onchange="mathExpiryDate(this)" type="text" class="form-control date-picker" ctype="datefield" name="manufacture_date"></td>');
                }
                if (rtn.data[index].expiry_date) {
                    html.push('<td><input name="expiry_date" type="text" value="' + rtn.data[index].expiry_date + '" readonly="readonly" style="background:#fafafa;"></td>');
                } else {
                    html.push('<td><input name="expiry_date" type="text"  readonly="readonly" style="background:#fafafa;"></td>');
                }
                html.push('<td td_name="purchase_num">' + rtn.data[index].purchase_num + '</td>');
                html.push('<td><input type="number" name="accept_num" style="width:130px;" min="1" oninput="validAcceptNum(this,' + (rtn.data[index].purchase_num) + ')" max="' + (rtn.data[index].purchase_num) + '" value=' + (rtn.data[index].purchase_num) + '></td>');
                html.push('<td style="text-align: center;">');
                html.push('<a class="btn-tools" href="javascript:void(0);" onclick="deleteRow(this)"><i class="am-icon-trash-o am-text-danger"></i></a>');
                html.push('</td>');
                html.push("</tr>");
                $("#contact_drugs_datatable").find("tbody").append(html.join(""));
                html = [];
            }
            bindDatePicker();
            total_purchase_num > 0 ? $("#contact_drugs_datatable").parent().parent().parent().parent().removeClass('hide') : '';
        }
    }, 'json');
}
//隐形镜片
function query_contact_lens() {
    $.post(query_url, {'entry_id': entry_id, 'typeid': 20}, function (rtn) {
        var html = [];
        if (rtn.data.length > 0) {
            var total_purchase_num = 0;
            for (var index in rtn.data) {
                if (rtn.data[index].purchase_num <= 0) {
                    continue;
                }
                total_purchase_num += rtn.data[index].purchase_num;
                var id = "'" + rtn.data[index].Id + "'";
                html.push('<tr rowid="' + index + '">');
                html.push('<td><div class="checkbox"><label><input type="checkbox"></label></div></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Id + '" name="id" style="display: none;" readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Products.Id + '" name="goods_id"  readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Products.ShelfLife + '" name="shelf_life" readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Snd.id + '" name="snd_id" readonly="true"/></td>');
                html.push('<td td_name="goods_name">' + productGroupName(rtn.data[index].Products) + '</td>');
                html.push('<td td_name="sph">' + rtn.data[index].Snd.sph + '</td>');
                html.push('<td td_name="cyl">' + rtn.data[index].Snd.cyl + '</td>');

                if (rtn.data[index].lot_number) {
                    html.push('<td><input name="lot_number" value="' + rtn.data[index].lot_number + '" readonly="readonly" style="background:#fafafa;" type="text"></td>');
                } else {
                    html.push('<td><input name="lot_number"  type="text"></td>');
                }
                if (rtn.data[index].manufacture_date) {
                    html.push('<td><input name="manufacture_date" value="' + rtn.data[index].manufacture_date + '" type="text" readonly="readonly" style="background:#fafafa;" ></td>');
                } else {
                    html.push('<td><input  name="manufacture_date" onchange="mathExpiryDate(this)" type="text" class="form-control date-picker" ctype="datefield" name="manufacture_date"></td>');
                }
                if (rtn.data[index].expiry_date) {
                    html.push('<td><input name="expiry_date" type="text" value="' + rtn.data[index].expiry_date + '" readonly="readonly" style="background:#fafafa;"></td>');
                } else {
                    html.push('<td><input name="expiry_date" type="text"  readonly="readonly" style="background:#fafafa;"></td>');
                }
                html.push('<td td_name="purchase_num">' + rtn.data[index].purchase_num + '</td>');
                html.push('<td><input type="number" name="accept_num" style="width:130px;" min="1" oninput="validAcceptNum(this,' + (rtn.data[index].purchase_num) + ')" max="' + (rtn.data[index].purchase_num) + '" value=' + (rtn.data[index].purchase_num) + '></td>');
                html.push('<td style="text-align: center;">');
                html.push('<a class="btn-tools" href="javascript:void(0);" onclick="deleteRow(this)"><i class="am-icon-trash-o am-text-danger"></i></a>');
                html.push('</td>');
                html.push("</tr>");
                $("#contact_lens_datatable").find("tbody").append(html.join(""));
                html = [];
            }
            bindDatePicker();
            total_purchase_num > 0 ? $("#contact_lens_datatable").parent().parent().parent().parent().removeClass('hide') : '';
        }
    }, 'json');
}

//护理产品
function query_care_solution() {

    $.post(query_url, {'entry_id': entry_id, 'typeid': 50}, function (rtn) {
        var html = [];
        if (rtn.data.length > 0) {
            var total_purchase_num = 0;
            for (var index in rtn.data) {
                if (rtn.data[index].purchase_num <= 0) {
                    continue;
                }
                total_purchase_num += rtn.data[index].purchase_num;
                html = [];
                var id = "'" + rtn.data[index].Id + "'";
                var type = "'contact_lens_care_solution'";
                html.push('<tr rowid="' + index + '">');
                html.push('<td><div class="checkbox"><label><input type="checkbox"><i></i></label></div></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Id + '" name="id" style="display: none;" readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Products.Id + '" name="goods_id"  readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="' + rtn.data[index].Products.ShelfLife + '" name="shelf_life" readonly="true"/></td>');
                html.push('<td style="display:none;"><input value="0" name="is_give" readonly="true"/></td>');
                html.push('<td td_name="goods_name">' + productGroupName(rtn.data[index].Products) + '</td>');
                if (rtn.data[index].lot_number) {
                    html.push('<td><input name="lot_number" value="' + rtn.data[index].lot_number + '" readonly="readonly" style="background:#fafafa;"  type="text"></td>');
                } else {
                    html.push('<td><input name="lot_number"  type="text"></td>');
                }
                if (rtn.data[index].manufacture_date) {
                    html.push('<td><input name="manufacture_date" value="' + rtn.data[index].manufacture_date + '" type="text" readonly="readonly" style="background:#fafafa;" ></td>');
                } else {
                    html.push('<td><input  name="manufacture_date" onchange="mathExpiryDate(this)" type="text" class="form-control date-picker" ctype="datefield" name="manufacture_date" format="yyyy-MM-dd" value=""></td>');
                }
                if (rtn.data[index].expiry_date) {
                    html.push('<td><input name="expiry_date" type="text" value="' + rtn.data[index].expiry_date + '" readonly="readonly" style="background:#fafafa;"></td>');
                } else {
                    html.push('<td><input name="expiry_date" type="text"  readonly="readonly" style="background:#fafafa;"></td>');
                }
                html.push('<td td_name="purchase_num">' + rtn.data[index].purchase_num + '</td>');
                html.push('<td><input type="number" name="accept_num" style="width:130px;" min="1" oninput="validAcceptNum(this,' + (rtn.data[index].purchase_num) + ')" max="' + (rtn.data[index].purchase_num) + '" value=' + (rtn.data[index].purchase_num) + '></td>');
                html.push('<td style="text-align: center;">');
                html.push('<a class="btn-tools" href="javascript:void(0);" onclick="deleteRow(this)"><i class="am-icon-trash-o am-text-danger"></i></a>');
                html.push('</td>');
                html.push("</tr>");
                $("#contact_lens_care_solution_datatable").find("tbody").append(html.join(""));
            }
            bindDatePicker();
            total_purchase_num > 0 ? $("#contact_lens_care_solution_datatable").parent().parent().parent().parent().removeClass('hide') : '';
        } else {
            $("#contact_lens_care_solution_datatable").parent().parent().hide();
            $("#contact_lens_care_solution_datatable").parent().parent().prev().hide();
        }
    }, 'json');
}

function validAcceptNum(obj, accept_num) {//验收数量不能填0--如果不验收改商品直接使用删除功能
    if ($(obj).val() < 1) {
        $(obj).val(1);
    }
    if ($(obj).val() > accept_num) {
        $(obj).val(accept_num);
    }
    var table_name = $(obj).parents("table").attr("id");
}

function deleteRow(obj) {
    var table_name = $(obj).parents("table").attr("id");
    $(obj).parents("tbody").find("tr[rowid='" + $(obj).parent().parent().attr("rowid") + "']").remove();
}

function batch_edit(goods_type, type) {
    var json = {};
    var table = [];
    $("#" + goods_type + "_datatable").find("tr[rowid]").find("input[type='checkbox']:checked").each(function () {
        json = {};
        json.rowid = $(this).parents("tr").attr("rowid");
        table.push(json);
    });
    if (table.length <= 0) {
        layer.alert("请勾选需要批量处理的数据");
        return;
    }
    if (type == 'batch') {
        if (!$("[name='" + goods_type + "_lot_number']").val() || !$("[name='" + goods_type + "_manufacture_date']").val()) {
            layer.alert("请填写批号和生产日期");
            return;
        }
    }
    if (type == 'batch') {
        for (var index in table) {
            $("#" + goods_type + "_datatable").find("tr[rowid='" + table[index].rowid + "']").find("[name='lot_number']").val($("[name='" + goods_type + "_lot_number']").val());
            $("#" + goods_type + "_datatable").find("tr[rowid='" + table[index].rowid + "']").find("[name='manufacture_date']").attr('value', $("[name='" + goods_type + "_manufacture_date']").val());
            mathExpiryDate($("#" + goods_type + "_datatable").find("tr[rowid='" + table[index].rowid + "']").find("[name='manufacture_date']")[0]);
        }
    } else if (type == 'clear') {
        for (var index in table) {
            $("#" + goods_type + "_datatable").find("tr[rowid='" + table[index].rowid + "']").find("[name='lot_number']").val('');
            $("#" + goods_type + "_datatable").find("tr[rowid='" + table[index].rowid + "']").find("[name='manufacture_date']").attr('value', '');
            $("#" + goods_type + "_datatable").find("tr[rowid='" + table[index].rowid + "']").find("[name='expiry_date']").val('');
        }
    }
    $("#" + goods_type + "_datatable").find("tr").find("input[type='checkbox']").removeAttr("checked");
    $("[name='" + goods_type + "_lot_number']").val('');
    $("[name='" + goods_type + "_manufacture_date']").attr('value', '');
}

function mathExpiryDate(obj) {
    if (!$(obj).val()) {
        $(obj).parent().parent().find("[name='expiry_date']").val("");
        return;
    }
    var date = new Date($(obj).val());
    var realNowDate = new Date(getFormatDate(new Date()));
    if (date >= realNowDate) {
        layer.alert("生产日期必须小于今日");
        return;
    }
    var mounth = parseInt($(obj).parent().parent().find("[name='shelf_life']").val());
    var ExpiryDate = DateAdd("m ", mounth, date);
    dateTime = ExpiryDate.setDate(ExpiryDate.getDate() - 1);//到期日期减一天
    ExpiryDate = new Date(ExpiryDate);
    var formatDate = getFormatDate(ExpiryDate);
    var days = mathExpir(formatDate); //计算是否在近效期内
    if (days <= 180 && days > 1) {
        layer.alert("该商品处于近效期内,请及时处理", function (index) {
            $(obj).parent().parent().find("[name='expiry_date']").val(formatDate);
            layer.close(index);
        });
    } else if (days <= 1) {
        layer.alert("该商品已经过期,不能验收");
        $(obj).parent().parent().find("[name='expiry_date']").val("");
        return;
    } else {
        $(obj).parent().parent().find("[name='expiry_date']").val(formatDate);
    }
}

function getFormatDate(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var date = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return year + "-" + month + "-" + date;
}

function mathExpir(ExpiryDate) {
    var ed = new Date(ExpiryDate);
    var days = Math.floor((ed - new Date()) / (24 * 3600 * 1000));
    return days;
}

function DateAdd(interval, number, date) {
    switch (interval) {
        case "y ": {
            date.setFullYear(date.getFullYear() + number);
            return date;
            break;
        }
        case "q ": {
            date.setMonth(date.getMonth() + number * 3);
            return date;
            break;
        }
        case "m ": {
            date.setMonth(date.getMonth() + number);
            return date;
            break;
        }
        case "w ": {
            date.setDate(date.getDate() + number * 7);
            return date;
            break;
        }
        case "d ": {
            date.setDate(date.getDate() + number);
            return date;
            break;
        }
        case "h ": {
            date.setHours(date.getHours() + number);
            return date;
            break;
        }
        case "m ": {
            date.setMinutes(date.getMinutes() + number);
            return date;
            break;
        }
        case "s ": {
            date.setSeconds(date.getSeconds() + number);
            return date;
            break;
        }
        default: {
            date.setDate(d.getDate() + number);
            return date;
            break;
        }
    }
}

function changeStorage(obj) {
    if ($(obj).getData().toStorage.length > 0) {
        $("#storage_house").parents(".filter-bar").slideDown();
    } else {
        $("[name='storehouse_id']").clearData();
        $("#storage_house").parents(".filter-bar").slideUp();
    }
}

function back() {
    var param = {};
    $.open("procurement.accept.inspect", param, "_self");
}

function save() {

    var _data = {
        entry_id: entry_id,
        datatablefull: [],
        datatable: [],
        datatable1: []
    };
    $("#contact_lens_datatable").find("tr[rowid]").each(function () {
        var data = {};
        data.entry_data_id = $(this).find("input[name='id']").val();
        data.goods_id = $(this).find("input[name='goods_id']").val();
        data.shelf_life = $(this).find("input[name='shelf_life']").val();
        data.snd_id = $(this).find("input[name='snd_id']").val();
        data.goods_name = $(this).find("td[td_name='goods_name']").text();
        data.sph = $(this).find("td[td_name='sph']").text();
        data.cyl = $(this).find("td[td_name='cyl']").text();
        data.lot_number = $(this).find("input[name='lot_number']").val();
        data.manufacture_date = $(this).find("input[name='manufacture_date']").val();
        data.expiry_date = $(this).find("input[name='expiry_date']").val();
        data.purchase_num = $(this).find("td[td_name='purchase_num']").text();
        data.accept_num = $(this).find("input[name='accept_num']").val();
        _data.datatable.push(data);
    });

    $("#contact_lens_care_solution_datatable").find("tr[rowid]").each(function () {
        var data = {};
        data.entry_data_id = $(this).find("input[name='id']").val();
        data.goods_id = $(this).find("input[name='goods_id']").val();
        data.shelf_life = $(this).find("input[name='shelf_life']").val();
        data.goods_name = $(this).find("td[td_name='goods_name']").text();
        data.lot_number = $(this).find("input[name='lot_number']").val();
        data.manufacture_date = $(this).find("input[name='manufacture_date']").val();
        data.expiry_date = $(this).find("input[name='expiry_date']").val();
        data.purchase_num = $(this).find("td[td_name='purchase_num']").text();
        data.accept_num = $(this).find("input[name='accept_num']").val();
        _data.datatable1.push(data);
    });

    $("#contact_drugs_datatable").find("tr[rowid]").each(function () {
        var data = {};
        data.entry_data_id = $(this).find("input[name='id']").val();
        data.goods_id = $(this).find("input[name='goods_id']").val();
        data.shelf_life = $(this).find("input[name='shelf_life']").val();
        data.goods_name = $(this).find("td[td_name='goods_name']").text();
        data.lot_number = $(this).find("input[name='lot_number']").val();
        data.manufacture_date = $(this).find("input[name='manufacture_date']").val();
        data.expiry_date = $(this).find("input[name='expiry_date']").val();
        data.purchase_num = $(this).find("td[td_name='purchase_num']").text();
        data.accept_num = $(this).find("input[name='accept_num']").val();
        _data.datatable1.push(data);
    });

    for (var index in _data.datatable) {
        if (!_data.datatable[index].lot_number) {
            layer.alert("请填入批号");
            return;
        }
        if (!_data.datatable[index].manufacture_date) {
            layer.alert("请填入生产日期");
            return;
        }
        if (!_data.datatable[index].expiry_date) {
            layer.alert("请填入失效日期");
            return;
        }
        if (_data.datatable[index].manufacture_date > _data.datatable[index].expiry_date) {
            layer.alert("失效日期不能小于生产日期");
            return;
        }
        if (!_data.datatable[index].accept_num) {
            layer.alert("请填入验收数量");
            return;
        }
    }
    for (var index in _data.datatable1) {
        if (!_data.datatable1[index].lot_number) {
            layer.alert("请填入批号");
            return;
        }
        if (!_data.datatable1[index].manufacture_date) {
            layer.alert("请填入生产日期");
            return;
        }
        if (!_data.datatable1[index].expiry_date) {
            layer.alert("请填入失效日期");
            return;
        }
        if (_data.datatable1[index].manufacture_date > _data.datatable1[index].expiry_date) {
            layer.alert("失效日期不能小于生产日期");
            return;
        }
        if (!_data.datatable1[index].accept_num) {
            layer.alert("请填入验收数量");
            return;
        }
    }
    if (_data.datatable.length <= 0 && _data.datatable1.length <= 0) {
        layer.alert("未找到验收商品");
        return;
    }
    if (!save_url) {
        layer.alert("参数错误");
        return;
    }
    if (_data.datatable.length > 0) {
        for (var i in _data.datatable) {
            _data.datatablefull.push(_data.datatable[i]);
        }
    }
    if (_data.datatable1.length > 0) {
        for (var i in _data.datatable1) {
            _data.datatablefull.push(_data.datatable1[i]);
        }
    }
    delete _data.datatable;
    delete _data.datatable1;
    _data.datatablefull = JSON.stringify(_data.datatablefull);
    $.post(save_url, _data, function (res) {
        if (res.code == 1) {
            layer.alert(res.msg);
            return false;
        }
        layer.alert("验收成功", function () {
            history.back();
        });
    }, 'json');
}
